package com.share;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class LoginActivity extends Activity {

	private hipro.user.Users webserviceUser;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		
		this.webserviceUser = new hipro.user.Users();
		this.webserviceUser.setWebservice(getString(R.string.webservice_user));

		// general login action
		this.loginAction();
	}

	/**
	 * Login action
	 * 
	 * @author Tien Nguyen
	 */
	private void loginAction() {
		Button btnLogin = (Button) findViewById(R.id.btnLogin);
		btnLogin.setOnClickListener(new OnClickBtnLogin());
	}

	/**
	 * Class on click button login
	 * 
	 * @author NguyenVanTien
	 * 
	 */
	private class OnClickBtnLogin implements OnClickListener {
		@Override
		public void onClick(View v) {
			//show waiting form
			//setContentView(R.layout.waiting);
		
			EditText eUsername = (EditText) v.getRootView().findViewById(
					R.id.txtUsername);
			EditText ePassword = (EditText) v.getRootView().findViewById(
					R.id.txtPassword);
			Log.d("Tien", "Username :" + eUsername.getText());
			Log.d("Tien", "Password :" + ePassword.getText());
			if (LoginActivity.this.webserviceUser.login(eUsername.getText().toString(),
					ePassword.getText().toString())) {

				SharedPreferences settings = getSharedPreferences("pref_login", 0);
				SharedPreferences.Editor editor = settings.edit();
				editor.putString("username", eUsername.getText().toString());
				editor.putString("password", ePassword.getText().toString());
				editor.commit();

				Intent intent = new Intent(LoginActivity.this,
						AndroidChiaSeThongTinActivity.class);
				startActivity(intent);
				LoginActivity.this.finish();
			}else{
				Toast.makeText(v.getRootView().getContext(), 
						"Login faild, Please check username and password", 
						Toast.LENGTH_LONG).show();
			}
			
			//setContentView(R.layout.login);
		}

	}
}
